package cn.backpackerxl.servlet;

import cn.backpackerxl.entity.Admin;
import cn.backpackerxl.service.AdminService;
import cn.backpackerxl.service.impl.AdminServiceImpl;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

import static cn.backpackerxl.util.MD5Utils.code;
import static cn.backpackerxl.util.isEmpty.isEmpty;

@WebServlet(name = "AdminServlet", value = "/admin")
public class AdminServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //设置编码格式
        request.setCharacterEncoding("utf-8");
        response.setContentType("text/json;charset=utf-8");
        response.setCharacterEncoding("utf-8");

        //获取不同的响应操作
        String action = request.getParameter("action");

        //使用反射机制执行不同的响应事件
        try {
            Method method = this.getClass().getDeclaredMethod(action, HttpServletRequest.class, HttpServletResponse.class);
            method.invoke(this, request, response);
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
    }

    /**
     * 登录处理事件
     *
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     */
    public void sing(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String email = request.getParameter("name");
        String passwd = request.getParameter("passwd");
        AdminService adminService = new AdminServiceImpl();
        Admin admin = adminService.findByEmail(email);

        if (admin == null) {
            request.setAttribute("error", " 用户不存在！");
            request.getRequestDispatcher("/sing").forward(request, response);
        } else {
            if (code(passwd).equals(admin.getPasswd())) {
                admin.setPasswd("");//释放密码
                request.getSession().setAttribute("name", admin.getName().substring(0, 1));
                response.sendRedirect(request.getContextPath());
            } else {
                request.setAttribute("error", " 邮箱或密码错误！");
                request.getRequestDispatcher("/sing").forward(request, response);
            }
        }
    }

    /**
     * 注册事件
     *
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     */
    public void singup(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String name = request.getParameter("name");
        String passwd = request.getParameter("passwd");
        String email = request.getParameter("email");
        String sex = request.getParameter("sex");
        String phone = request.getParameter("phone");
        String verification = request.getParameter("verification");
        Admin admin = new Admin();
        admin.setName(name.trim());
        admin.setSex(Integer.parseInt(sex));
        admin.setPasswd(code(passwd.trim()));
        admin.setEmail(email.trim());
        admin.setPhone(phone.trim());
        if (verification.equalsIgnoreCase((String) request.getSession().getAttribute("checkLoginCode"))) {
            AdminService adminService = new AdminServiceImpl();
            if (!isEmpty(adminService.findByEmail(email.trim()))) {
                request.setAttribute("error", " 此邮箱已被注册！");
                request.getRequestDispatcher("/singup").forward(request, response);
            } else if (!isEmpty(adminService.findByPhone(phone.trim()))) {
                request.setAttribute("error", " 此手机号已被注册！");
                request.getRequestDispatcher("/singup").forward(request, response);
            } else {
                int i = adminService.addAdmin(admin);
                if (i == 0) {
                    request.setAttribute("error", " 稍后再试！");
                    request.getRequestDispatcher("/singup").forward(request, response);
                } else {
                    response.sendRedirect(request.getContextPath() + "/sing");
                }
            }
        } else {
            request.setAttribute("error", " 验证码错误！");
            request.getRequestDispatcher("/singup").forward(request, response);
        }
    }

    /**
     * 退出登录事件
     *
     * @param request
     * @param response
     * @throws IOException
     */
    public void signOut(HttpServletRequest request, HttpServletResponse response) throws IOException {
        request.getSession().removeAttribute("name");
        response.sendRedirect(request.getContextPath() + "/sing");
    }
}
